package com.code.app.http;

import android.content.Context;

import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

    private static IHttpEngine httpEngine = new OkHttpEngine();

    private String url;

    private Map<String, Object> params;

    private HttpMethod httpMethod = HttpMethod.GET;

    private Context context;

    public static void init(IHttpEngine newHttpEngine) {
        httpEngine = newHttpEngine;
    }

    private HttpUtils(Context context) {
        this.context = context;
        this.params = new HashMap<>();
    }

    public static HttpUtils with(Context context) {
        return new HttpUtils(context);
    }

    public HttpUtils exChange(IHttpEngine newHttpEngine) {
        httpEngine = newHttpEngine;
        return this;
    }

    public HttpUtils url(String url) {
        this.url = url;
        return this;
    }

    public HttpUtils get() {
        this.httpMethod = HttpMethod.GET;
        return this;
    }

    public HttpUtils post() {
        this.httpMethod = HttpMethod.POST;
        return this;
    }

    public HttpUtils params(Map<String, Object> params) {
        this.params.putAll(params);
        return this;
    }

    public HttpUtils params(String key, Object value) {
        this.params.put(key, value);
        return this;
    }

    public void execute(EngineCallBack engineCallBack) {
        if (engineCallBack == null) {
            engineCallBack = EngineCallBack.DEFAULT_CALL_BACK;
        }

        if (this.httpMethod.equals(HttpMethod.GET)) {
            get(url, params, engineCallBack);
        }

        if (this.httpMethod.equals(HttpMethod.POST)) {
            post(url, params, engineCallBack);
        }
    }

    public void execute() {
        execute(null);
    }


    private void get(String url, Map<String, Object> params, EngineCallBack engineCallBack) {
        httpEngine.get(url, params, engineCallBack);
    }

    private void post(String url, Map<String, Object> params, EngineCallBack engineCallBack) {
        httpEngine.post(url, params, engineCallBack);
    }

    public enum HttpMethod {

        POST(0), GET(1);

        private int code;

        HttpMethod(int code) {
            this.code = code;
        }

        public int getCode() {
            return code;
        }
    }

}
